package com.tailyou.androidlearning202400.adapter

import android.graphics.Color
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.tailyou.androidlearning202400.R
import com.tailyou.androidlearning202400.adapter.AdapterMain.MViewHolder
import com.tailyou.androidlearning202400.beans.EntryBean
import java.util.Random

class AdapterMain(// 列表要显示的数据，通过构造函数传递进来
    private val data: List<EntryBean>
) : RecyclerView.Adapter<MViewHolder>() {

    private lateinit var onItemClickListener: OnItemClickListener

    interface OnItemClickListener {
        fun onItemClick(position: Int)
    }

    fun setOnItemClickListener(onItemClickListener: OnItemClickListener) {
        this.onItemClickListener = onItemClickListener
    }

    /**
     * 根据布局文件item_rv_main生成ViewHolder
     */
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MViewHolder {
        val view = LayoutInflater.from(parent.context).inflate(R.layout.item_rv_main, parent, false)
        return MViewHolder(view)
    }

    /**
     * 把数据绑定到布局上
     */
    override fun onBindViewHolder(holder: MViewHolder, position: Int) {
        val random = Random()
        holder.viewLeft.setBackgroundColor(
            Color.argb(
                255, random.nextInt(255), random.nextInt(255), random.nextInt(255)
            )
        )
        holder.tvName.text = data[position].name
        holder.tvDate.text = data[position].date
        holder.itemView.setOnClickListener {
            onItemClickListener.onItemClick(position)
        }
    }

    /**
     * 返回列表数据条数
     */
    override fun getItemCount(): Int {
        return data.size
    }

    /**
     * ViewHolder对item_rv_main中的组件进行封装和初始化
     */
    class MViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        var viewLeft: View = itemView.findViewById(R.id.viewLeft)
        var tvName: TextView = itemView.findViewById(R.id.tvName)
        var tvDate: TextView = itemView.findViewById(R.id.tvDate)
    }
}
